//
//  NetworkTools.swift
//  1.新浪微博
//
//  Created by 温泉 on 16/3/4.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

//网络请求枚举类型，swift中的枚举可以指定不同的数据类型
enum CZRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {

    // MARK:- 应用程序信息

    let appkey = "575870939"
    let appSecret = "ca302e36ed6815361bcc96b5ed098ff3"
    let redirectUri = "http://www.baidu.com"
    
    // 单例
    static let sharedTools:NetworkTools = {
        let tools = NetworkTools(baseURL: nil)
        
        //设置反序列化支持数据格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/pain")
        
        return tools
    }()
    
    
    func request(Method:CZRequestMethod, URLString:String, parameters:[String: AnyObject]?, finished:(result:[String: AnyObject]?)->()) {
        
        // 回调方法的参数，可以从AFN 的方法中直接黏贴
        // 成功回调
        
        let success = {
            (task:NSURLSessionTask,responseObject:AnyObject?) -> Void in
            
            if let result = responseObject as? [String:AnyObject] {
                finished(result: result)
            }else{
                print("数据格式错误")
                finished(result: nil)
            }
        }
        
        let failure = { (task:NSURLSessionDataTask?, error: NSError) -> Void in
            print("网络请求错误\(error)")
            finished(result:nil)
            
        }
        
        if Method == .GET{
            //GET请求
            GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            // POST请求
            POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }

}
